package com.ravi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ravi.common.constant.CheckExceptionEnum;
import com.ravi.common.exception.CheckException;
import com.ravi.mapper.RoomTypeMapper;
import com.ravi.model.dto.RoomTypeDto;
import com.ravi.model.entity.RoomType;
import com.ravi.service.intf.RoomTypeService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class RoomTypeServiceImpl implements RoomTypeService {

	@Autowired
	private RoomTypeMapper roomTypeMapper;

	@Override
	public PageInfo<RoomTypeDto> getRoomTypePage(Integer pageNum, Integer pageSize) {
		pageNum = (null == pageNum) || (pageNum <= 0) ? 1 : pageNum;
		PageHelper.startPage(pageNum, pageSize);
		List<RoomType> roomTypes = roomTypeMapper.getAll();
		List<RoomTypeDto> dtos = getRoomTypeDtos(roomTypes);
		return new PageInfo<>(dtos);
	}

	@Override
	public List<RoomTypeDto> getRoomTypeSearch(String keyword) {
		List<RoomType> roomTypeList = roomTypeMapper.getRoomTypesByName(keyword);
		return getRoomTypeDtos(roomTypeList);
	}

	private List<RoomTypeDto> getRoomTypeDtos(List<RoomType> roomTypeList) {
		if (ObjectUtils.isEmpty(roomTypeList)) {
			throw new CheckException(CheckExceptionEnum.SEARCH_FAILED);
		}
		List<RoomTypeDto> ret = new CopyOnWriteArrayList<>();
		for (RoomType roomType : roomTypeList) {
			if (roomType.getPreTypeId() == -1) {
				RoomTypeDto norm = SetRoomTypeDto(roomType);
				ret.add(norm);
			}else {
				RoomType preRoomType = roomTypeMapper.getRoomTypeById(roomType.getPreTypeId());
				RoomTypeDto havePre = SetRoomTypeDto(roomType);
				havePre.setPreTypeId(preRoomType.getId());
				havePre.setPreTypeName(preRoomType.getRoomType());
				ret.add(havePre);
			}
		}
		return ret;
	}

	@Override
	public List<RoomTypeDto> getAll() {
		List<RoomType> roomTypeList = roomTypeMapper.getAll();
		return getRoomTypeDtos(roomTypeList);
	}

	private RoomTypeDto SetRoomTypeDto(RoomType roomType) {
		RoomTypeDto dto = new RoomTypeDto();
		dto.setId(roomType.getId());
		dto.setRoomType(roomType.getRoomType());
		dto.setPreTypeId(-1);
		dto.setPreTypeName("无");
		dto.setJoinFlag(roomType.getJoinFlag());
		dto.setCheckTime(roomType.getCheckTime());
		dto.setSerialNum(roomType.getSerialNum());
		return dto;
	}
}
